package com.example.elmmerchants.Sign;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.elmmerchants.Create_Shop.Set_Shop_Data;
import com.example.elmmerchants.Email.SendEmail;
import com.example.elmmerchants.First_Page_Fragment.First_Page;
import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Add_Merchant_SQL;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Password_Login_Method extends Fragment {

    View root;
    Button login_btn;
    EditText account, password;

    Context context;
    AlertDialog dialog;
    boolean is_in_db = false;
    boolean is_approved = false, is_loading_data = false, is_update_data = false;
    String user_email = "";
    String shop_status, qualification_status, legal_status, first_category, second_category;
    String android_id;

    public Password_Login_Method(Context context, String android_id) {
        this.context = context;
        this.android_id = android_id;
    }

    private class Loading_Data_Thread extends Thread{
        @Override
        public void run() {
            is_approved = false;
            is_in_db = false;
            is_loading_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE user_name = ? And password = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, account.getText().toString());
                    preparedStatement.setString(2, password.getText().toString());
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getString("user_name").equals(account.getText().toString()) && set.getString("password").equals(password.getText().toString())) {
                            is_in_db = true;
                            user_email = set.getString("email");
                            first_category = set.getString("first_category");
                            second_category = set.getString("second_category");
                            if (set.getInt("shop_information") == 1) {
                                shop_status = "已录入";
                            }
                            else {
                                shop_status = "待录入";
                            }

                            if (set.getInt("qualification_information") == 1) {
                                qualification_status = "已录入";
                            }
                            else {
                                qualification_status = "待录入";
                            }

                            if (set.getInt("legal_information") == 1) {
                                legal_status = "已录入";
                            }
                            else {
                                legal_status = "待录入";
                            }
                            if (set.getInt("approved") == 1) {
                                is_approved = true;
                            }
                        }
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                while (!is_loading_data) {
                    try{
                        Thread.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (is_in_db) {
                            if (is_approved) {
                                Update_Android_ID_Go_To_First_Page_Thread updateAndroidIdGoToFirstPageThread = new Update_Android_ID_Go_To_First_Page_Thread();
                                updateAndroidIdGoToFirstPageThread.start();
                            }
                            else {
                                Update_Android_ID_Go_To_Create_Shop_Page_Thread updateAndroidIdGoToCreateShopPageThread = new Update_Android_ID_Go_To_Create_Shop_Page_Thread();
                                updateAndroidIdGoToCreateShopPageThread.start();
                            }
                        }
                        else {
                            Toast.makeText(context, "No this Account", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            });
        }
    }

    private class Update_Android_ID_Go_To_Create_Shop_Page_Thread extends Thread {
        @Override
        public void run() {
            is_update_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `elm`.`merchant` set phone_id = ? WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, android_id);
                    preparedStatement.setString(2, user_email);
                    preparedStatement.executeUpdate();
                    is_update_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_update_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(context, Set_Shop_Data.class);
                    intent.putExtra("user_email", user_email);
                    intent.putExtra("first_category", first_category);
                    intent.putExtra("second_category", second_category);
                    intent.putExtra("shop_information_status", shop_status);
                    intent.putExtra("qualification_information_status", qualification_status);
                    intent.putExtra("legal_information_status", legal_status);
                    startActivity(intent);
                    getActivity().finish();
                }
            });
        }
    }

    private class Update_Android_ID_Go_To_First_Page_Thread extends Thread {
        @Override
        public void run() {
            is_update_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "update `elm`.`merchant` set phone_id = ? WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, android_id);
                    preparedStatement.setString(2, user_email);
                    preparedStatement.executeUpdate();
                    is_update_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_update_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(context, First_Page.class);
                    intent.putExtra("email", user_email);
                    startActivity(intent);
                    getActivity().finish();
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_password__login__method, container, false);

        account = root.findViewById(R.id.account);
        password = root.findViewById(R.id.password);

        login_btn = root.findViewById(R.id.login_btn);
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (account.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
                    Toast.makeText(root.getContext(), "Please Input All Data", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();
                    Loading_Data_Thread loadingDataThread = new Loading_Data_Thread();
                    loadingDataThread.start();
                }
            }
        });

        return root;
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
        LayoutInflater inflater1 = LayoutInflater.from(root.getContext());
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}